package org.http.annotation;

import org.reflections.Reflections;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author andy
 */
public class AnnotationManger {

    public static Map<String, ExecutorBean> getPathMethod(String packageName) {
        Reflections reflections = new Reflections(packageName);
        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Controller.class,true);

        // 存放url和ExecutorBean的对应关系
        Map<String, ExecutorBean> myapp = new HashMap<>(10);
        for (Class<?> classes : classesList) {
            StringBuilder classPathAnnotation = new StringBuilder();
            // 取得类上的path路径
            Path classesAnnotation = classes.getAnnotation(Path.class);
            if(null != classesAnnotation){
                classPathAnnotation = new StringBuilder("/".equals(classesAnnotation.value()) ? "" : classesAnnotation.value());
                if(classPathAnnotation.toString().endsWith("/")){
                    classPathAnnotation = new StringBuilder(classPathAnnotation.substring(0, classPathAnnotation.length() - 1));
                }
            }
            // 得到该类下面的所有方法
            Method[] methods = classes.getDeclaredMethods();

            for (Method method : methods) {
                // 得到该类下面的Path注解
                Path pathAnnotation = method.getAnnotation(Path.class);
                if (null != pathAnnotation) {
                    ExecutorBean executorBean = new ExecutorBean();
                    try {
                        executorBean.setObject(classes.getDeclaredConstructor().newInstance());
                    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    executorBean.setMethod(method);
                    if(!"".equals(pathAnnotation.value()) && !pathAnnotation.value().startsWith("/")){
                        classPathAnnotation.append("/").append(pathAnnotation.value());
                    }
                    myapp.put(classPathAnnotation + pathAnnotation.value(), executorBean);
                }
            }
        }
        return myapp;
    }

}
